package com.mixsmart.mobile.interceptor;

import java.net.URLDecoder;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.ui.ModelMap;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.mixsmart.commonweb.IWebConstant;
import com.mixsmart.commonweb.helper.HttpRequestHelper;
import com.mixsmart.core.config.SystemConfig;
import com.mixsmart.utils.StringUtils;

/**
 * 访问请求拦截器
 * @author lmq
 * @version 1.0
 * @since JDK版本大于等于1.6
 * 2016年1月25日
 */
public class ACLInterceptor implements HandlerInterceptor {

	private static final Logger logger = Logger.getLogger(ACLInterceptor.class);
	
	private List<String> excludeMaps;
	
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object obj, Exception arg3)
			throws Exception {
	}

	@SuppressWarnings("unchecked")
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response,
			Object obj, ModelAndView modelAndView) throws Exception {
		if(null != modelAndView) {
			ModelMap modelMap = modelAndView.getModelMap();
			modelMap.put("currentUri", HttpRequestHelper.getCurrentUri(request));
			modelMap.put("currentUriParam", HttpRequestHelper.getCurrentUriParam(request));
			modelMap.put("project", SystemConfig.getInstance().getProjectInfo());
			//请求参数添加到map里面
			Map<String,String[]> curParamMaps = request.getParameterMap();
			if(null != curParamMaps && curParamMaps.size()>0) {
				for (String key : curParamMaps.keySet()) {
					String[] values = curParamMaps.get(key);
					if(values.length<2) {
						if(values[0].length()<100) {
							if(StringUtils.isNotEmpty(values[0]) && values[0].startsWith("%")) {
								modelMap.put(key, URLDecoder.decode(values[0], "UTF-8"));
							} else {
								modelMap.put(key, values[0]);
							}
						}
					}
				}
			} //if;
			modelMap.put("mobileTheme", SystemConfig.getInstance().getValue("mobile.theme"));
			RedirectView redirectView = ((RedirectView)modelAndView.getView());
			if(null == redirectView || !redirectView.isRedirectView()) {
				if(isLogin(request)) {
					modelMap.put("userInfo", HttpRequestHelper.getUserInfoFromSession(request));
				}
			}
		}
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object obj) throws Exception {
		boolean is = false;
		String currentUri = HttpRequestHelper.getCurrentUri(request);
		if(isLogin(request)) {
			//LogFactory.record(busiLog, request,null);
			is = true;
		} else {
			if(!isExclude(currentUri)) {
				logger.debug("拦截URL【"+currentUri+"】");
				HttpSession session = request.getSession();
				session.setAttribute(IWebConstant.SESSION_LOGIN_BEFORE_URI, currentUri);
				String loginUri = "/login.do";
				String contextPath = request.getContextPath();
				if(StringUtils.isNotEmpty(contextPath) && !"/".equals(contextPath)) {
					loginUri = contextPath+loginUri;
				}
				response.sendRedirect(loginUri);
			} else {
				is = true;
			}
		}
		return is;
	}
	
	/**
	 * 是否排除
	 * @param currentUri 当前请求uri
	 * @return 是返回：true；否则返回：false
	 */
	private boolean isExclude(String currentUri) {
		boolean is = false;
		is = currentUri.startsWith("#");
		if(!is && null != excludeMaps && excludeMaps.size()>0) {
			for (String uri : excludeMaps) {
				if(StringUtils.isNotEmpty(uri) && uri.trim().length()>1 && uri.indexOf("*")>0) {
					uri = uri.replace("*", "");
					if(currentUri.startsWith(uri) || currentUri.endsWith(uri)) {
						is = true;
						break;
					}
				} else {
					if(currentUri.equals(uri)) {
						is = true;
						break;
					}
				}
			}
		}
		return is;
	}
	
	
	/**
	 * 判断用户是否登录
	 * @param request Http请求对象
	 * @return 登录返回：true；否则返回：false
	 */
	private boolean isLogin(HttpServletRequest request) {
		boolean is = false;
		HttpSession session = request.getSession();
		if(null != session) {
			try { 
				is = (null != session.getAttribute(IWebConstant.SESSION_USER_KEY))?true:false;
			} catch (Exception e) {
				is = false;
			}
		}
		return is;
	}

	
	///////getter and setter///////
	
	public List<String> getExcludeMaps() {
		return excludeMaps;
	}

	public void setExcludeMaps(List<String> excludeMaps) {
		this.excludeMaps = excludeMaps;
	}
	
}
